package com.xiaozhen.blog.filter;

import com.alibaba.fastjson.JSON;
import com.xiaozhen.blog.service.impl.LoginUser;
import com.xiaozhen.blog.utils.CookieUtil;
import com.xiaozhen.blog.utils.JwtUtil;
import com.xiaozhen.blog.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @create 2023-05-12 16:14
 * 过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从 cookie 中获取 token
        String cookieToken = CookieUtil.getValue(request, "token");
        System.out.println();
        System.out.println("获取 token 成功，获取到的 cookieToken 为：" + cookieToken);
        System.out.println();
        if (!StringUtils.hasText(cookieToken)) {
            // 如果 cookieToken 为 null，则放行
            filterChain.doFilter(request, response);
            return;
        }
        // 解析 token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(cookieToken);
            userId = claims.getSubject();
            System.out.println("userId :" + userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token 非法");
        }
        // 从 redis 中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = JSON.parseObject(redisCache.getCacheObject(redisKey), LoginUser.class);

        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }

        // 存入 SecurityContextHolder
        // TODO 获取权限信息封装到 Authentication 中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);

    }
}
